<template>
  <div class="word-learning-page">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <div>
        <span>抗遗忘复习（共{{ displayedWords.length }}词）</span>
      </div>
      <div class="top-nav__right">
        <!-- 倍速播放控制（点击展开/收起） -->
        <div ref="speedControlRef" class="speed-control">
          <!-- 速度显示/触发按钮 -->
          <el-button
            class="speed-control__trigger"
            size="medium"
            :icon="showSpeedSlider ? 'fa-solid fa-chevron-up' : 'fa-solid fa-tachometer-alt'"
            @click="toggleSpeedSlider"
          >
            {{ playbackSpeed.toFixed(1) }}x
          </el-button>

          <!-- 展开后的滑块区域 -->
          <div
            v-if="showSpeedSlider"
            class="speed-control__slider-wrap"
          >
            <!-- 滑块 -->
            <el-slider
              v-model="playbackSpeed"
              :min="0.5"
              :max="2"
              :step="0.1"
              :format-tooltip="formatSpeed"
              class="speed-slider"
            />

            <!-- 复位按钮 -->
            <el-button
              class="speed-control__reset-btn"
              size="mini"
              @click="resetSpeed"
            >
              复位 1.0x
            </el-button>
          </div>
        </div>

        <!-- 发音切换 (美式/英式) -->
        <el-button
          class="nav-btn accent-btn"
          size="medium"
          :class="{ 'is-active': true }"
          @click="toggleAccent"
        >
          <span>{{ isAmerican ? '美音' : '英音' }}</span>
        </el-button>

        <!-- 音标显示/隐藏 -->
        <el-button
          class="nav-btn phonetic-btn"
          size="medium"
          @click="togglePhonetic"
        >
          <span :class="['phonetic-label', { 'is-off': !showPhonetic }]">音标</span>
        </el-button>
      </div>
    </header>

    <!-- 中间滚动列表区域 -->
    <main class="word-list-container">
      <div v-if="displayedWords.length > 0" class="word-list">
        <div
          v-for="(word, index) in displayedWords"
          :key="index"
          class="word-item"
          :class="{
            'word-known': word.status === 'known',
            'word-unknown': word.status === 'unknown'
          }"
          @click="playPronunciation(word,index)"
        >
          <!-- 单词和音标 -->
          <div class="word-info">
            <div class="word-main">
              <h3 class="word-text"><span
                @click.stop="playEn(word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : 'I don\'t know')"
              >{{ word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : '🤔' }}</span></h3>
              <p v-if="showPhonetic" class="word-phonetic">
                <span>{{ isAmerican ? word.phoneticAm : word.phoneticBr }}</span>
              </p>

              <!-- 单词意思 -->
              <div v-if="word.clickCount % 3 === 2" class="word-meaning">
                <span @click.stop="playZh(word.wordMeaning.replace(/[A-Za-z]/g, ''))">{{ word.wordMeaning }}</span>
              </div>
            </div>

            <!-- 添加短语例句按钮 -->
            <el-button
              v-if="word.extendedInfo"
              icon="fa-solid fa-book-open"
              class="phrase-btn"
              size="small"
              @click.stop="showPhraseExample(word)"
            />

            <!-- 快速标记按钮 -->
            <div class="quick-actions">
              <el-button
                icon="fa-solid fa-heart"
                class="quick-btn"
                :class="{ 'unknown-btn': word.status === 'unknown' }"
                @click.stop="toggleUnknown(index)"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <el-empty description="这里空空的"></el-empty>
      </div>
    </main>

    <!-- 底部统计栏 -->
    <footer class="bottom-nav">
      <div>
        <span>遗忘 {{ unknownCount }} 个单词</span>
      </div>
      <div class="word-actions">
        <!-- 能认识 -->
        <!--        <div class="can-learn">-->
        <!--          <span>😀</span>-->
        <!--          <span class="badge">{{ knownCount }}</span>-->
        <!--        </div>-->
        <!-- 不认识 -->
        <div class="not-learn">
          <span>😔</span>
          <span class="badge">{{ unknownCount }}</span>
        </div>
      </div>
      <div class="div-btns">
        <label class="checkbox-label">
          <input v-model="canKnowWord" type="checkbox" class="checkbox-input">
          <span class="checkbox-text">屏蔽学新已认识</span>
        </label>
        <el-button
          v-if="!this.$route.query.trulyReview"
          class="nav-btn start-learn"
          size="medium"
          :disabled="displayedWords.length === 0"
          @click="submitCheckData"
        >
          <i class="fa-solid fa-floppy-disk"/>
          提交结果
        </el-button>
      </div>
    </footer>

    <WordDetailDrawer
      :word="currentWordDetail"
      :visible="drawer"
      @update:visible="drawer=false"
    />
  </div>
</template>

<script>
import { courseAfter, submitCheckData } from '@/api/wordSystemCourse'
import AudioCacheUtil from '@/utils/AudioCacheUtil'
import { antiForgetListPush, antiForgetListPushBath, getAntiForgetWordBatch } from '@/api/antiForget'
import WordDetailDrawer from '@/views/course/component/courseTeach/wordLearning/WordDetailDrawer.vue'

export default {
  name: 'AntiForgetReview',
  components: { WordDetailDrawer },
  data() {
    return {
      isAmerican: true, // 美式发音
      showPhonetic: true, // 显示音标
      playbackSpeed: 1.0, // 播放速度
      // 新增：控制倍速滑块展开/收起
      showSpeedSlider: false,

      // 单词数据
      displayedWordsBack: [], // 显示的单词备份
      displayedWords: [], // 显示的单词

      nowClickWord: {},

      canKnowWord: true, // 屏蔽单词与否

      currentWordDetail: {},
      drawer: false
    }
  },
  computed: {
    knownCount() {
      return this.displayedWords.filter(w => w.status === 'known').length
    },
    unknownCount() {
      return this.displayedWords.filter(w => w.status === 'unknown').length
    }
  },
  watch: {
    // 判断当前点击的按钮是否为连续点击 如果不是 需要将上一次的按钮点击次数清零
    'nowClickWord'(newValue, oldValue) {
      if (newValue.id !== oldValue.id) {
        oldValue.clickCount = 0
      }
    },
    'canKnowWord'(newValue) {
      if (newValue) {
        this.displayedWords = this.displayedWordsBack.filter(item => item.knowNoStudy === '0')
      } else {
        this.displayedWords = this.displayedWordsBack
      }
    }
  },
  created() {
    this.loadWordData()
  },
  // ✅ 新增：组件销毁时清除监听
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside)
  },
  methods: {
    showPhraseExample(word) {
      this.drawer = true
      this.currentWordDetail = word
    },
    async loadWordData() {
      let res = {}
      if (this.$route.query.cid) {
        res = await courseAfter({ cid: this.$route.query.cid })
      } else if (this.$route.query.idArr) {
        res.studyWordList = await getAntiForgetWordBatch(JSON.parse(this.$route.query.idArr))
      } else {
        return
      }
      res.studyWordList.forEach(item => {
        item.clickCount = 0
        item.status = ''
      })
      this.displayedWordsBack = res.studyWordList
      this.displayedWords = []
      if (this.canKnowWord) {
        this.displayedWords = res.studyWordList.filter(item => item.knowNoStudy === '0')
      } else {
        this.displayedWords = res.studyWordList
      }
    },
    async submitCheckData() {
      const idArr = []
      this.displayedWords.forEach(item => {
        if (item.status === 'unknown') {
          idArr.push(item.libraryTypeWordId)
        }
      })
      if (!this.$route.query.idArr) {
        await antiForgetListPush({
            antiForgetId: this.$route.query.q1,
            cid: this.$route.query.cid
          },
          idArr
        )
        this.$router.push({ path: `/antiForgetFeedback?antiForgetId=${this.$route.query.q1}&canKnowWord=${this.canKnowWord}` })
      } else if (this.$route.query.idArr) {
        const obj = JSON.parse(this.$route.query.idArr)
        const antiForgetIdArr = []
        obj.forEach(item => {
          item.libTypeWordIdList = idArr
          antiForgetIdArr.push(item.antiForgetId)
        })
        await antiForgetListPushBath(obj)
        this.$router.push({ path: `/antiForgetFeedback?antiForgetIdArr=${JSON.stringify(antiForgetIdArr)}&canKnowWord=${this.canKnowWord}` })
      } else {
        this.$notify({ type: 'error', message: '找不到请求服务器' })
      }
    },

    // 格式化速度显示
    formatSpeed(value) {
      return `${value}x`
    },

    // 切换发音（美式/英式）
    toggleAccent() {
      this.isAmerican = !this.isAmerican
    },

    // 切换音标显示/隐藏
    togglePhonetic() {
      this.showPhonetic = !this.showPhonetic
    },

    // 播放单词发音
    playPronunciation(word) {
      AudioCacheUtil.play(word.fullSpell ? word.fullSpell : word.wordFullSpell, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
      word.clickCount++
      this.nowClickWord = word
    },

    playZh(text) {
      AudioCacheUtil.play(text, 'zh', this.playbackSpeed)
    },
    playEn(text) {
      AudioCacheUtil.play(text, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },

    // 新增：切换倍速滑块显示/隐藏
    toggleSpeedSlider() {
      this.showSpeedSlider = !this.showSpeedSlider

      // ✅ 如果展开，则绑定 document 点击监听；否则解绑
      if (this.showSpeedSlider) {
        document.addEventListener('click', this.handleClickOutside)
      } else {
        document.removeEventListener('click', this.handleClickOutside)
      }
    },

    // ✅ 新增：点击外部关闭滑块
    handleClickOutside(e) {
      const controlEl = this.$refs.speedControlRef
      if (controlEl && !controlEl.contains(e.target)) {
        this.showSpeedSlider = false
        document.removeEventListener('click', this.handleClickOutside)
      }
    },

    // 新增：复位播放速度到1.0x
    resetSpeed() {
      this.playbackSpeed = 1.0
      // 复位后可选择自动收起滑块
      this.showSpeedSlider = false
      document.removeEventListener('click', this.handleClickOutside) // ✅ 防止监听残留
    },

    // 切换“认识”按钮
    toggleKnown(index) {
      const word = this.displayedWords[index]
      if (word.status === 'known') {
        word.status = null // 再点一次取消
      } else {
        word.status = 'known' // 互斥，覆盖为 known
      }
    },

    // 切换“不认识”按钮
    toggleUnknown(index) {
      const word = this.displayedWords[index]
      if (word.status === 'unknown') {
        word.status = null
      } else {
        word.status = 'unknown'
      }
    }
  }
}
</script>

<style scoped>
* {
  user-select: none;
}

.word-learning-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #f5f7fa;
}

/* 中间单词列表区域 */
.word-list-container {
  flex-grow: 1;
  overflow: hidden;
  padding: 5px;
}

.word-list {
  height: 100%;
  overflow-y: auto;
}

.word-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  user-select: none;
}

.word-main {
  flex-grow: 1;
}

.word-text {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  width: 100%;

  position: relative;

  span {
    cursor: pointer;
  }
}

.word-phonetic {
  font-size: 18px;
  color: #999;
  margin: 10px 0 0 0;
  font-style: italic;
}

.word-meaning {
  color: #555;
  margin-top: 20px;

  span {
    cursor: pointer;
  }
}

.quick-actions {
  display: flex;
  gap: 5px;
}

.quick-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0;
  border-radius: 50%;
  background-color: transparent; /* 默认透明 */
  border: 1px solid #ccc; /* 给个轻微边框 */
  color: #555;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  background-color: #f5f5f5;
}

.known-btn {
  background-color: #e6f7ed !important;
  color: #239744 !important;
  border-color: #239744 !important;
}

.unknown-btn {
  background-color: #fde2e2 !important;
  color: #e53e3e !important;
  border-color: #e53e3e !important;
}

/* 底部菜单栏 */
.bottom-nav {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  align-items: center;
  height: 56px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

/* 滚动条美化 */
.word-list::-webkit-scrollbar {
  width: 0;
}

/* 顶部导航栏整体样式 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 左右布局分离 */
  padding: 0 16px;
  height: 50px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  position: relative; /* 为滑块下拉层提供定位基准 */
}

/* 右侧功能区容器（统一靠右） */
.top-nav__right {
  display: flex;
  align-items: center;
  gap: 12px; /* 按钮间距统一 */
}

/* 统一按钮基础样式 */
.nav-btn {
  padding: 8px 12px;
  border-radius: 20px; /* 圆角更柔和 */
  background-color: transparent;
  color: #333;
  transition: all 0.2s ease;
  border: 1px solid transparent;
  font-size: 14px;
}

.nav-btn:hover {
  background-color: #f5f7fa;
  border-color: #e0e0e0;
}

.start-learn {
  border: 1px solid #e0e0e0;
}

.start-learn:hover {
  color: #0084ff;
}

/* 发音按钮激活态（增强视觉反馈） */
.accent-btn.is-active {
  background-color: #e6f4ea;
  color: #239744;
  border-color: #d1e7dd;
}

/* 倍速控制容器 */
.speed-control {
  position: relative; /* 滑块下拉层相对定位 */
  display: flex;
  align-items: center;
}

/* 倍速触发按钮 */
.speed-control__trigger {
  padding: 8px 12px;
  border-radius: 20px;
  background-color: #f5f7fa;
  color: #333;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px; /* 图标与文字间距 */
}

.speed-control__trigger:hover {
  background-color: #e9ecef;
  border-color: #dee2e6;
}

/* 倍速滑块容器（下拉层） */
.speed-control__slider-wrap {
  position: absolute;
  top: 60px; /* 位于触发按钮下方 */
  left: -50px;
  width: 220px;
  padding: 12px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 20; /* 确保在其他元素上方 */
  /* 淡入动画 */
  animation: fadeIn 0.2s ease forwards;
}

/* 滑块样式 */
.speed-slider {
  flex-grow: 1;
  margin: 0;
}

/* 复位按钮样式 */
.speed-control__reset-btn {
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #f0f9ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.speed-control__reset-btn:hover {
  background-color: #e6f7ff;
  border-color: #69c0ff;
}

/* 音标按钮样式（保持原有逻辑，优化细节） */
.phonetic-label {
  position: relative;
  display: inline-block;
  padding: 0 2px;
  color: #333;
  transition: color 0.2s ease;
}

.phonetic-label::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  height: 2px;
  top: 50%;
  transform: translateY(-50%) scaleX(0);
  transform-origin: left center;
  background: #ff4d4f; /* 横线用醒目红色 */
  transition: transform 0.25s cubic-bezier(.2, .9, .2, 1);
  pointer-events: none;
}

.phonetic-label.is-off {
  color: #999;
}

.phonetic-label.is-off::after {
  transform: translateY(-50%) scaleX(1);
}

/* 淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.phonetic-btn {
  margin: 0;
}

/* 默认卡片样式 */
.word-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 10px;
  margin-top: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

/* 认识状态：淡绿色背景 */
.word-item.word-known {
  background-color: #e6f7ed;
  border: 1px solid #239744;
}

/* 不认识状态：淡红色背景 */
.word-item.word-unknown {
  background-color: #fde2e2;
  border: 1px solid #e53e3e;
}

/* 按钮默认透明，选中时保留高亮 */
.quick-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0;
  border-radius: 50%;
  background-color: transparent;
  border: 1px solid #ccc;
  color: #555;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  background-color: #f5f5f5;
}

.known-btn {
  background-color: #239744 !important;
  color: #fff !important;
  border-color: #239744 !important;
}

.unknown-btn {
  background-color: #e53e3e !important;
  color: #fff !important;
  border-color: #e53e3e !important;
}

.word-actions {
  display: flex;
  gap: 40px;
  margin-top: 12px;
  margin-bottom: 12px;
  position: relative;

  div {
    font-size: 40px;
  }

  .not-learn {
    color: rgb(229, 62, 62);
  }

  .can-learn {
    color: rgb(35, 151, 68);
  }
}

.word-actions > div {
  position: relative;
  font-size: 40px;
}

/* 徽标样式 */
.badge {
  position: absolute;
  top: -6px;
  right: -10px;
  min-width: 20px;
  height: 20px;
  padding: 0 6px;
  border-radius: 10px;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
  line-height: 20px;
  text-align: center;
}

/* 认识用绿色徽标 */
.can-learn .badge {
  background-color: #52c41a;
}

/* 不认识用红色徽标 */
.not-learn .badge {
  background-color: #ff4d4f;
}

.word-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #00b578;
}

.word-item:hover span,
.word-item:hover h3 {
  color: white;
}

.div-btns {
  display: flex;
  flex-direction: row;
}

/* 复选框 */
.checkbox-label {
  display: flex;
  align-items: center;
  margin-right: 22px;
  cursor: pointer;
  gap: 6px;
  font-size: 14px;
  color: #333;
  transition: color 0.2s ease;
}

.checkbox-input {
  appearance: none;
  width: 16px;
  height: 16px;
  border: 2px solid #34a853;
  border-radius: 4px;
  position: relative;
  transition: all 0.2s ease;
}

.checkbox-input:checked {
  background-color: #34a853;
}

.checkbox-input:checked::after {
  content: '✓';
  position: absolute;
  color: #fff;
  font-size: 12px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.checkbox-input:checked + .checkbox-text {
  color: #34a853;
  font-weight: 500;
}

/* 短语例句按钮样式 */
.phrase-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0 8px;
  border-radius: 50%;
  background-color: #f0f7ff !important;
  color: #1890ff !important;
  border-color: #91d5ff !important;
  transition: all 0.25s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.phrase-btn:hover {
  background-color: #e6f7ff !important;
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.phrase-btn:active {
  transform: scale(0.95);
}

</style>
